﻿using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using DocumentFormat.OpenXml.Drawing.Diagrams;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Admin.NET.Application;

/// <summary>
/// 设备运行日志服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class DeviceLogService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<DeviceLog> _deviceLogRep;
    private readonly ILogger<DeviceLogService> logger;

    public DeviceLogService(SqlSugarRepository<DeviceLog> deviceLogRep, ILogger<DeviceLogService> logger)
    {
        _deviceLogRep = deviceLogRep;
        this.logger = logger;
    }

    /// <summary>
    /// 分页查询设备运行日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询设备运行日志")]
    public async Task<SqlSugarPagedList<DeviceLogOutput>> Page(PageDeviceLogInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();
        var query = _deviceLogRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.Title.Contains(input.SearchKey)
                || u.ReceiveText.Contains(input.SearchKey)
                || u.Ip.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.Title), u => u.Title.Contains(input.Title.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ReceiveText), u => u.ReceiveText.Contains(input.ReceiveText.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Ip), u => u.Ip.Contains(input.Ip.Trim()))
            .WhereIF(input.GateWayId > 0, u => u.GateWayId == input.GateWayId)
            .WhereIF(input.DeviceId > 0, u => u.DeviceId == input.DeviceId)
            .WhereIF(input.CreateTimeRange != null && input.CreateTimeRange.Length == 2, u => u.CreateTime >= input.CreateTimeRange[0] && u.CreateTime <= input.CreateTimeRange[1])
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<DeviceGateWay>((u, gatewayid) => u.GateWayId == gatewayid.Id)
            .LeftJoin<DeviceInfo>((u, gatewayid, deviceid) => u.DeviceId == deviceid.Id)
            .Select((u, gatewayid, deviceid) => new DeviceLogOutput
            {
                Id = u.Id,
                Title = u.Title,
                ReceiveText = u.ReceiveText,
                Ip = u.Ip,
                GateWayId = u.GateWayId,
                GateWayIdGateWayName = gatewayid.GateWayName,
                DeviceId = u.DeviceId,
                DeviceIdDeviceName = deviceid.DeviceName,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                DeviceProcotolProessResult=u.DeviceProcotolProessResult
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加设备运行日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加设备运行日志")]
    public async Task<long> Add(AddDeviceLogInput input)
    {
        var entity = input.Adapt<DeviceLog>();
        await _deviceLogRep.CopyNew().InsertAsync(entity);
        return entity.Id;
    }

    public async Task<long> AddNoThrow(AddDeviceLogInput input)
    {
        try
        {
            return await Add(input);
        }
        catch (Exception ex)
        {
            throw ex;
            //logger.LogError(ex, "");
            //return 0;
        }
    }

    /// <summary>
    /// 删除设备运行日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除设备运行日志")]
    public async Task Delete(DeleteDeviceLogInput input)
    {
        var entity = await _deviceLogRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _deviceLogRep.FakeDeleteAsync(entity);   //假删除
        //await _deviceLogRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新设备运行日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新设备运行日志")]
    public async Task Update(UpdateDeviceLogInput input)
    {
        var entity = input.Adapt<DeviceLog>();
        await _deviceLogRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取设备运行日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取设备运行日志")]
    public async Task<DeviceLog> Detail([FromQuery] QueryByIdDeviceLogInput input)
    {
        return await _deviceLogRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取设备运行日志列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取设备运行日志列表")]
    public async Task<List<DeviceLogOutput>> List([FromQuery] PageDeviceLogInput input)
    {
        return await _deviceLogRep.AsQueryable().Select<DeviceLogOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取网关列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeviceGateWayGateWayIdDropdown"), HttpGet]
    [DisplayName("获取网关列表")]
    public async Task<dynamic> DeviceGateWayGateWayIdDropdown()
    {
        return await _deviceLogRep.Context.Queryable<DeviceGateWay>()
                .Select(u => new
                {
                    Label = u.GateWayName,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    /// <summary>
    /// 获取设备列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeviceInfoDeviceIdDropdown"), HttpGet]
    [DisplayName("获取设备列表")]
    public async Task<dynamic> DeviceInfoDeviceIdDropdown()
    {
        return await _deviceLogRep.Context.Queryable<DeviceInfo>()
                .Select(u => new
                {
                    Label = u.DeviceName,
                    Value = u.Id
                }
                ).ToListAsync();
    }
}